package com.ansion.baseui.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.ansion.utils.ResourceUtils;

import java.util.List;


/**
 * created by zhaoyuntao
 * on 13/10/2022
 * description:
 */
class BroadcastSupport {
    private BroadcastReceiver broadcastReceiver;

    void _registerBroadcast(@NonNull List<BroadcastProcessor> processors, @NonNull List<String> categories) {
        if (!processors.isEmpty()) {
            IntentFilter intentFilter = new IntentFilter();
            for (BroadcastProcessor processor : processors) {
                processor.setParam(intentFilter);
            }
            for (String category : categories) {
                intentFilter.addCategory(category);
            }
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    for (BroadcastProcessor processor : processors) {
                        if (processor.matched(intent.getAction())) {
                            processor.onProcess(intent);
                            break;
                        }
                    }
                }
            };
            LocalBroadcastManager.getInstance(ResourceUtils.getContext()).registerReceiver(broadcastReceiver, intentFilter);
        }
    }

    void _unregisterBroadcast() {
        if (broadcastReceiver != null) {
            LocalBroadcastManager.getInstance(ResourceUtils.getContext()).unregisterReceiver(broadcastReceiver);
        }
    }
}
